package redis

import (
	"errors"

	"fmt"
	"github.com/go-redis/redis"
	"runtime"
)

type Client struct {
	Addresses string
	Client    *redis.Client
}

func NewClient(addresses string, password string) (*Client, error) {
	option := &redis.Options{
		Addr:       addresses,
		Password:   "",
		DB:         0,
		MaxRetries: 7,
		PoolSize:   20 * runtime.NumCPU(),
	}
	if password != "" {
		option.Password = password
	}

	client := redis.NewClient(option)
	if _, err := client.Ping().Result(); nil != err {
		fmt.Println("REDIS CLIENT ERR:", err)
		return nil, err
	}

	return &Client{Addresses: addresses, Client: client}, nil
}

func (c *Client) LPop(key string) (string, error) {
	if key == "" {
		return "", errors.New("key is empty")
	}
	result, err := c.Client.LPop(key).Result()
	if err != nil {
		return result, err
	}
	return result, nil
}

func (c *Client) RPop(key string) (string, error) {
	if key == "" {
		return "", errors.New("key is empty")
	}

	result, err := c.Client.RPop(key).Result()
	if err != nil {
		return result, err
	}
	return result, nil
}

func (c *Client) LPush(key string, values ...string) error {
	if key == "" {
		return errors.New("key is empty")
	}

	if nil == values {
		return errors.New("value is empty")
	}
	if err := c.Client.LPush(key, values).Err(); err != nil {
		return err
	}
	return nil
}

func (c *Client) RPush(key string, values ...string) error {
	if key == "" {
		return errors.New("key is empty")
	}

	if nil != values {
		return errors.New("value is empty")
	}
	if err := c.Client.RPush(key, values).Err(); err != nil {
		return err
	}
	return nil
}

func (c *Client) Close() error {
	return c.Client.Close()
}
